var SEA = require('./sea');
var Gun = SEA.Gun;
//var then = require('./then');

// eslint-disable-next-line no-unused-vars
function User(root) {
  this._ = { $: this };
}
User.prototype = (function() {
  function F() {}
  F.prototype = Gun.chain;
  return new F();
})(); // Object.create polyfill
User.prototype.constructor = User;

// let's extend the gun chain with a `user` function.
// only one user can be logged in at a time, per gun instance.
Gun.chain.user = function(pub) {
  var gun = this,
    root = gun.back(-1),
    user;
  if (pub) {
    return root.get('~' + pub);
  }
  if ((user = root.back('user'))) {
    return user;
  }
  // FIXME: Was a redeclaration. What instance should `at` and `uuid` be?
  root = root._;
  var at = root,
    uuid = at.opt.uuid || Gun.state.lex;
  (at = (user = at.user = gun.chain(new User()))._).opt = {};
  at.opt.uuid = function(cb) {
    var id = uuid(),
      pub = root.user;
    if (!pub || !(pub = pub._.sea) || !(pub = pub.pub)) {
      return id;
    }
    id = id + '~' + pub + '.';
    if (cb && cb.call) {
      cb(null, id);
    }
    return id;
  };
  return user;
};
Gun.User = User;
module.exports = User;
